from datetime import datetime
from sqlalchemy import Column, String, Float, Integer, DateTime, Enum, JSON
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class OrderRecord(Base):
    """订单持久化模型"""
    __tablename__ = 'orders'

    id = Column(Integer, primary_key=True)
    order_id = Column(String(64), unique=True, nullable=False)
    symbol = Column(String(32), index=True, nullable=False)
    side = Column(Enum('BUY', 'SELL', name='order_side'), nullable=False)
    order_type = Column(Enum('LIMIT', 'MARKET', name='order_type'))
    quantity = Column(Integer, nullable=False)
    price = Column(Float)
    status = Column(Enum('SUBMITTED', 'PARTIAL_FILLED', 'FILLED', 'CANCELED', name='order_status'))
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, onupdate=datetime.utcnow)
    # metadata = Column(JSON)  # 存储原始API响应等扩展信息


class PositionSnapshot(Base):
    """仓位快照模型"""
    __tablename__ = 'position_snapshots'

    id = Column(Integer, primary_key=True)
    symbol = Column(String(32), index=True, nullable=False)
    timestamp = Column(DateTime, default=datetime.utcnow, index=True)
    confirmed_long = Column(Integer, default=0)
    confirmed_short = Column(Integer, default=0)
    pending_long = Column(Integer, default=0)
    pending_short = Column(Integer, default=0)
    avg_price = Column(Float)


class TradeSignal(Base):
    """交易信号记录"""
    __tablename__ = 'trade_signals'

    id = Column(Integer, primary_key=True)
    signal_id = Column(String(64), unique=True)
    symbol = Column(String(32), index=True)
    signal_type = Column(Enum('LONG', 'SHORT', 'CLOSE', name='signal_type'))
    entry_price = Column(Float)
    stop_loss = Column(Float)
    volatility = Column(Float)
    generated_at = Column(DateTime, default=datetime.utcnow)
    executed = Column(Enum('PENDING', 'SUCCESS', 'FAILED', name='execution_status'))